import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;

/*
 Please leave all portions of the program regarding java.swing.text alone for now.
 It is the intention to get it working at a later time where we can colour code and change font.
 For now, it is simply working the way a normal textArea would work, so there is no harm done.
 */

public class Client implements Runnable, ActionListener
{
    // Components for the visual display of the chat windows
    private String username;
    private ClientGUI gui;
    // The socket connecting us to the server
    private Socket socket;
    // The streams we communicate to the server; these come
    // from the socket
    private DataOutputStream dout;
    private DataInputStream din;
    // Constructor
    public Client (String host, int port, String username)
    {
	this.gui = new ClientGUI(this);
	this.username = username;
	// Connect to the server
	try
	{
	    // Initiate the connection
	    socket = new Socket (host, port);
	    // We got a connection! Tell the world
	    System.out.println ("connected to " + socket);
	    // Let's grab the streams and create DataInput/Output streams
	    // from them
	    din = new DataInputStream (socket.getInputStream ());
	    dout = new DataOutputStream (socket.getOutputStream ());
	    // Start a background thread for receiving messages
	    new Thread (this).start ();
	}
	catch (IOException ie)
	{
	    System.out.println (ie);
	}
	declareUser ();

    }


    // Tells the Server we're a new user and prints out new user information
    private void declareUser ()
    {

	try
	{
	    dout.writeUTF (this.getUsername ());
	}
	catch (IOException ie)
	{
	    System.out.println (ie);
	}
    }

    public void actionPerformed(ActionEvent e)
    {
	processMessage(e.getActionCommand());
	TextField tf = (TextField)(e.getSource());
	tf.setText("");
    }
    // Gets called when the user types something
    private void processMessage (String message)
    {
	try
	{
	    // Send it to the server
	    dout.writeUTF (message);
	}
	catch (IOException ie)
	{
	    System.out.println (ie);
	}
    }


    // Return the username
    public String getUsername ()
    {
	return this.username;
    }


    // Background thread runs this: show messages from other window
    public void run ()
    {
	try
	{
	    // Receive messages one-by-one, forever
	    while (true)
	    {
		// Get the next message
		String message = din.readUTF ();
		// Print it to our text window
		try
		{
		    gui.appendMessage(message);
		}
		catch (Exception e)
		{
		    System.out.println (e);
		}
	    }
	}
	catch (IOException ie)
	{
	    System.out.println (ie);
	}
    }


    public static void main (String args[])
    {

	//new Client( "127.0.0.1", 1337, "darksteel" );
	new Client (args [0], Integer.parseInt (args [1]), args [2]);
    }
}
